package com.aliyuncs.aui.service.impl;

import com.aliyuncs.aui.common.utils.MySQLUtil;
import com.aliyuncs.aui.dto.res.OrdersInfoResponse;
import com.aliyuncs.aui.dto.res.OrdersListResponse;
import com.aliyuncs.aui.dto.res.CommonResponse;
import com.aliyuncs.aui.dto.res.OrdersCreateResponse;
import com.aliyuncs.aui.service.OrdersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OrdersServiceImpl implements OrdersService {
    private static final Logger log = LoggerFactory.getLogger(OrdersServiceImpl.class);
    private final MySQLUtil mySQLUtil;

    public OrdersServiceImpl(MySQLUtil mySQLUtil) {
        this.mySQLUtil = mySQLUtil;
    }

    @Override
    public OrdersCreateResponse createOrders(String tenantId, String status) {
        String orderId = UUID.randomUUID().toString();
        String sql = "INSERT INTO orders (order_id, tenant_id, status) VALUES (?, ?, ?)";
        //String sql = "INSERT INTO session (session_id, type, role, log, created_at, user_id, tenant_id) VALUES (?, ?, ?, ?, NOW(), ?, ?)";
        
        try {
            int affectedRows = mySQLUtil.executeUpdate(sql, orderId, tenantId, status);
            if (affectedRows > 0) {
                return OrdersCreateResponse.builder()
                        .code(200)
                        .message("orders created successfully")
                        .OrdersId(orderId)
                        .build();
            }
            return OrdersCreateResponse.builder()
                    .code(500)
                    .message("Failed to create orders")
                    .build();
        } catch (SQLException e) {
            log.error("Create orders failed", e);
            return OrdersCreateResponse.builder()
                    .code(500)
                    .message("Database error: " + e.getMessage())
                    .build();
        }
    }



    @Override
    public OrdersInfoResponse getOrdersInfo(String orderId) {
        String sql = "SELECT * FROM orders WHERE order_id = ?";
        
        try (ResultSet rs = mySQLUtil.executeQuery(sql, orderId)) {
            if (rs.next()) {
                return OrdersInfoResponse.builder()
                        .code(200)
                        .message("Order found")
                        .resvId(rs.getString("resv_id"))
                        .takeoutId(rs.getString("takeout_id"))
                        .sessionId(rs.getString("session_id"))
                        .status(rs.getString("status"))
                        .build();
            } else {
                return OrdersInfoResponse.builder()
                        .code(404)
                        .message("Order not found")
                        .build();
            }
        } catch (SQLException e) {
            log.error("Failed to get order info", e);
            return OrdersInfoResponse.builder()
                    .code(500)
                    .message("Failed to get order info: " + e.getMessage())
                    .build();
        }
    }

    @Override
    public OrdersListResponse getOrdersList(String tenantId, String status) {
        String sql = "SELECT * FROM orders WHERE tenant_id = ?" + 
                    (status != null ? " AND status = ?" : "");
        
        try (ResultSet rs = status != null ? 
                mySQLUtil.executeQuery(sql, tenantId, status) :
                mySQLUtil.executeQuery(sql, tenantId)) {
            
            List<OrdersListResponse.OrderInfo> orders = new ArrayList<>();
            while (rs.next()) {
                orders.add(OrdersListResponse.OrderInfo.builder()
                    .orderId(rs.getString("order_id"))
                    .status(rs.getString("status"))
                    .build());
            }
            
            return OrdersListResponse.builder()
                    .code(200)
                    .message("Orders found")
                    .orders(orders)
                    .build();
        } catch (SQLException e) {
            log.error("Failed to get orders list", e);
            return OrdersListResponse.builder()
                    .code(500)
                    .message("Failed to get orders list: " + e.getMessage())
                    .build();
        }
    }

    @Override
    public CommonResponse updateOrdersInfo(String orderId, String status, 
            String resvId, String takeoutId, String sessionId) {
        StringBuilder sql = new StringBuilder("UPDATE orders SET ");
        List<Object> params = new ArrayList<>();
        
        if (status != null) {
            sql.append("status = ?, ");
            params.add(status);
        }
        if (resvId != null) {
            sql.append("resv_id = ?, ");
            params.add(resvId);
        }
        if (takeoutId != null) {
            sql.append("takeout_id = ?, ");
            params.add(takeoutId);
        }
        if (sessionId != null) {
            sql.append("session_id = ?, ");
            params.add(sessionId);
        }
        
        // Remove trailing comma and space
        sql.delete(sql.length() - 2, sql.length());
        sql.append(" WHERE order_id = ?");
        params.add(orderId);
        
        try {
            int rowsUpdated = mySQLUtil.executeUpdate(sql.toString(), params.toArray());
            if (rowsUpdated > 0) {
                return CommonResponse.builder()
                        .code(200)
                        .message("Order updated successfully")
                        .build();
            } else {
                return CommonResponse.builder()
                        .code(404)
                        .message("Order not found")
                        .build();
            }
        } catch (SQLException e) {
            log.error("Failed to update order", e);
            return CommonResponse.builder()
                    .code(500)
                    .message("Failed to update order: " + e.getMessage())
                    .build();
        }
    }
}
